//
//  CarInsuranceViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/14.
//

import UIKit
import WebKit
class CarInsuranceViewController: BaseViewController {
    var messageBtn: UIButton!
    var newMesRed: UIView!//信息红点
    var webView: WKWebView!
    var carInsuranceModel: CarInsuranceDataModel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initNav()
        self.view.backgroundColor = Theme.F5Color
        let config = WKWebViewConfiguration.init()
        let prefer = WKPreferences()
        prefer.javaScriptEnabled = true
        config.preferences = prefer
        
        self.webView = WKWebView.init(frame: CGRect(x: 14, y: 0, width: kScreenWidth - 28, height: 270))
        self.webView.configuration.userContentController.add(self, name: "h5ToApp") //提共js调用的方法
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        self.webView.autoresizesSubviews = true
        self.webView.allowsBackForwardNavigationGestures = false
        self.webView.scrollView.showsVerticalScrollIndicator = false
        self.webView.scrollView.showsHorizontalScrollIndicator = false
        self.webView.isUserInteractionEnabled = true
        self.webView.scrollView.isUserInteractionEnabled = true
        self.webView.scrollView.isScrollEnabled = true
        self.webView.sizeToFit()
        self.view.addSubview(self.webView)
        //self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
        
        self.webView.snp.makeConstraints{ make in
            make.top.equalTo(NavBarHight)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(kScreenHeight - TabbarHeight - NavBarHight)
        }
        self.requestGetCarinsurance()
        //self.requestGetArticleList()
    }
    
    func initNav(){
        let titleLab = UILabel(frame: CGRect(x: 18, y: NavBarHight - 40, width: 220, height: 30))
        titleLab.textColor = Theme.titleLabColor
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleLab.text = MMLocalizedString("car_insurance", comment: "汽车保险")
        titleLab.backgroundColor = .white
        self.navBar.addSubview(titleLab)
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        self.messageBtn = UIButton(frame: CGRect(x: kScreenWidth - 75, y: NavBarHight - 40, width: 30, height: 30))
        self.messageBtn.setImage(UIImage(named: "icon_news_msg"), for: .normal)
        self.messageBtn.contentMode = .scaleAspectFill
        self.messageBtn.addTarget(self, action: #selector(messageBtnAtion), for: .touchUpInside)
        self.navBar.addSubview(self.messageBtn)
        
        
        self.newMesRed = UIView(frame: CGRect(x: self.messageBtn.frame.size.width - 12, y: 4, width: 4, height: 4))
        self.newMesRed.backgroundColor = Theme.redColor
        self.newMesRed.layer.cornerRadius = 2
        self.newMesRed.layer.masksToBounds = true
        self.newMesRed.isHidden = true
        self.messageBtn.addSubview(self.newMesRed)
        
        let setBtn = UIButton(frame: CGRect(x: kScreenWidth - 42, y: NavBarHight - 40, width: 30, height: 30))
        setBtn.setImage(UIImage(named: "icon_news_set"), for: .normal)
        setBtn.addTarget(self, action: #selector(setBtnAntion), for: .touchUpInside)
        self.navBar.addSubview(setBtn)
    }
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        ///监听webView.scrollview的大小
        //        if keyPath == "contentSize" {
        //            if self.webView.frame.size.height < self.webView.scrollView.contentSize.height {
        //                self.webViewHeight = self.webView.scrollView.contentSize.height
        //                self.webView.snp.updateConstraints { (make) in
        //                    make.height.equalTo(self.webViewHeight)
        //                }
        //                self.updateConstraints()
        //                if self.webViewHeightBlock != nil {
        //                    self.webViewHeightBlock()
        //                }
        //            }
        //        }
    }
    
    //MARK: - Request
    //APP车保-查看内容
    func requestGetCarinsurance(){
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.carinsurance,objectType: CarInsuranceModel.self) { data in
            let resultObj = data as! CarInsuranceModel
            self.view.handleLoading()
            if resultObj.code == "1" {
                self.carInsuranceModel = resultObj.data
            }
            //self.tableView.reloadData()
            self.webViewLoadHtml()
        }error: { err in
            self.view.handleLoading()
        }
    }
    
    private func webViewLoadHtml(){
        let bottom_title = MMLocalizedString("get_quote", comment: "取得报价")
        
        let htmlStr = self.carInsuranceModel?.content ?? ""
        let formatWeb = """
                <!DOCTYPEhtml>
                    <html>
                    <head>
                        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                        <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                    </head>
                    <style type="text/css">
                        img{
                            display:inline-block;
                            max-width:100%@;
                        }
                    </style>
                    <script>
                        function btnAction(){
                                try {
                                    window.webkit.messageHandlers.h5ToApp.postMessage("就是一个消息啊")
                                }catch (e) {
                                    console.log(e)
                                }
                        }
                    </script>
                     
                    <body style="padding-left:10px; font-family:PingFangSC-Regular, padding-right:10px; padding-top:0px; background-color:#f5f5f5;">
                        <div style="background-color:#ffffff; padding:20px;">%@</div>
                        <div style="text-align: center;" onClick="btnAction()">
                            <div style="margin-left: 0px; margin-right:0px; height: 46px; margin-top: 40px; line-height: 46px; border-radius:8px; background-color: #005C99; color: white; font-size:16px;" >
                                    \(bottom_title)
                            </div>
                        </div>
                </body>
                    </html>
                """
        let contentStr = String(format: formatWeb,"%", htmlStr)
        self.webView.loadHTMLString(XTManageCenter.getHtmlLocalScaleString(htmlStr: contentStr), baseURL: nil)
    }
    
    //    //车保-查看
    //    func requestGetArticleList(){
    //        let param = ["code": "CARINSURANCE"]
    //        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.articleList(param: param),objectType: CarInsuranceModel.self) { data in
    //            let resultObj = data as! CarInsuranceModel
    //            if resultObj.code == "1" {
    ////                self.carInsuranceModel = resultObj.data
    //            }
    //            self.tableView.reloadData()
    //        }error: { err in
    //        }
    //    }
    //
    
    
    //MARK: - Antion
    //信息
    @objc func messageBtnAtion(){
        if UserModule.shared.isLogined == false{
            guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
                return
            }
            let vc = LoginViewController()
            let loginNavi = BaseNavigationController.init(rootViewController: vc)
            loginNavi.modalPresentationStyle = .fullScreen
            tabbarVC.present(loginNavi, animated: true)
            return
        }
        let vc = MessageViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //个人中心
    @objc func setBtnAntion(){
        if UserModule.shared.isLogined == false{
            let vc = LoginViewController()
            let loginNavi = BaseNavigationController.init(rootViewController: vc)
            loginNavi.modalPresentationStyle = .fullScreen
            self.present(loginNavi, animated: true)
            return
        }
        
        let vc = UserCenterViewController()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    ///取得报价
    private func getQuoteBtnAntion(){
        let vc = WebViewController()
        vc.urlStr = self.carInsuranceModel?.imageUrl ?? ""
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension CarInsuranceViewController: WKScriptMessageHandler, WKNavigationDelegate{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "h5ToApp" {
            //取得报价
            self.getQuoteBtnAntion()
        }
    }
}
